﻿using BCL.BaseLib;
using BCL.Tool;
using BCL.Tool.Extend;
using BCL.WPFComponent.Base;
using Devices;
using DevicesView;
using DevicesView.Logic.Test;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using XiaonuanPMS.Entity;
using XiaonuanPMS.Entity.View;
using XiaonuanPMS.Logic;
using BCL.BaseLib.Basics;
using BCL.WPFComponent;
namespace XiaonuanPMS
{

    /// <summary>
    /// UCTestNew.xaml 的交互逻辑
    /// </summary>
    public partial class UCTestNew : BaseFunctionControl
    {

        private TestingsLogic logic;// = new Logic.TestingsLogic();
        private List<TestInfoSource> tests;
        private DevicesView.Logic.Test.ResultLogic resultLogic;
        private List<BitmapImage> images;
        private List<UCTestResult> ucTestResults;
        private RPResult rPBreedDatas;
        private List<RPDataDic> rpSexs;
        private List<RPDataDic> rpPetTypes;


        public UCTestNew()
        {
            InitializeComponent();
        }
        public UCTestNew(FunctionEntity fe)
        {
            InitializeComponent();
            ucTestResults = new List<UCTestResult>();
        }

        public override void LanguageBinding()
        {
         
        }
        public override void ReloadData(object data)
        {
            base.ReloadData(data);
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            logic = new Logic.TestingsLogic();
            resultLogic = new DevicesView.Logic.Test.ResultLogic();
            images = new List<BitmapImage>
            {
                File.ReadAllBytes("image/icon_d4.png").ToBitmap(),
                File.ReadAllBytes("image/return.png").ToBitmap(),
                File.ReadAllBytes("image/restart.png").ToBitmap()
            };

            Devices.DevicesCollection.CommandCompleted += Item_CommandCompleted;
            Devices.DevicesCollection.DevicesCountChanged += DevicesCollection_DevicesCountChanged;

            DevicesCollection_DevicesCountChanged();
            dateEditStart.SelectedDate = DateTime.Today;
            dateEditEnd.SelectedDate = DateTime.Today.AddDays(1);
            DataRefresh();
        }
        private void DataRefresh()
        {
            tests = logic.GetTestInfos((DateTime)dateEditStart.SelectedDate, (DateTime)dateEditEnd.SelectedDate);
            tests?.ForEach(o => o.Images = images);
            this.gridControl1.ItemsSource = tests;
        }

        private void Item_CommandCompleted(Devices.Command sender, Devices.Result e)
        {
            if (e.ResultDatas == null)
                return;
            TestInfo info = tests?.FirstOrDefault(o => o.CMD != null && o.CMD.Id == sender.Id);
            if (info != null)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    info.CMD.Result = e;
                    info.Send = 2;
                    info.Devices = 1;
                    gridControl1.ItemsSource = null;
                    gridControl1.ItemsSource = tests;
                    foreach (TabItem item in MainTag.Items)
                        if ((IDevices)item.Tag == e.Devices || item.Tag == null)
                            (item.Content as UCTestResult).SetResult(e);
                }));
            }

        }
        /// <summary>
        /// 保存结果
        /// </summary>
        /// <param name="uc"></param>
        /// <param name="cmd"></param>
        private void Ucall_SaveCommandIng(UCTestResult uc, Command cmd)
        {
            if (!logic.SaveResult(cmd))
            {
                BCL.WPFComponent.UCMessageBox.Show("保存失败".Language());
                return;
            }
            resultLogic.RemoveCompleted(cmd.Result);
            foreach (TabItem item in MainTag.Items)
                (item.Content as UCTestResult).RemoveCmds(cmd);

            TestInfoSource info = null;
            if (tests != null)
                info = tests.FirstOrDefault(o => o.CMD != null && o.CMD.Id == cmd.Id);
            if (info != null)
            {
                tests.Remove(info);
                gridControl1.ItemsSource = null;
                gridControl1.ItemsSource = tests;
            }
        }
        private void DevicesCollection_DevicesCountChanged()
        {
            this.MainTag.Items.Clear();
            List<Devices.IDevices> devs = Devices.DevicesCollection.Devices;

            this.Dispatcher.Invoke(new Action(() =>
            {
                TabItem pageall = new TabItem { Header = "全部".Language(), IsSelected = true, Style = (Style)this.FindResource("TabItemStyle") };
                UCTestResult ucall = new UCTestResult();
                ucall.SaveCommandIng += Ucall_SaveCommandIng;
                ucall.DeleteCommanded += Ucall_DeleteCommanded;
                pageall.Content = ucall;
                this.MainTag.Items.Add(pageall);
                ucTestResults.Add(ucall);
                devs?.ForEach(o =>
                {
                    TabItem page = new TabItem { Header = o.Info.DisplayName, Tag = o, Style = (Style)this.FindResource("TabItemStyle") };
                    UCTestResult ucdev = new UCTestResult(o);
                    ucdev.SaveCommandIng += Ucall_SaveCommandIng;
                    ucdev.DeleteCommanded += Ucall_DeleteCommanded;
                    page.Content = ucdev;
                    this.MainTag.Items.Add(page);
                    ucTestResults.Add(ucdev);
                });
            }));
        }

        private void Ucall_DeleteCommanded(UCTestResult arg1, Command cmd)
        {

            TestInfoSource info = tests?.FirstOrDefault(o => o.CMD != null && o.CMD.Id == cmd.Id);
            if (info != null)
            {
                gridControl1.SelectedItem = info;
                Image_MouseDown(null, null);
            }
            else
            {
                ///已删除
                cmd.Status = 128;
                cmd?.Devices?.RemoveCommand(cmd.Id);
                new ResultLogic().RemoveCompleted(cmd.Result);
                foreach (TabItem item in MainTag.Items)
                    if ((IDevices)item.Tag == cmd.Devices || item.Tag == null)
                        (item.Content as UCTestResult).RemoveCmds(cmd);
            }

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DataRefresh();
        }

        private void Image_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (!(gridControl1.SelectedItem is TestInfoSource info))
                return;
            List<TestInfoSource> items = gridControl1.ItemsSource as List<TestInfoSource>;
            if (info.Send == 1 && CancelCmd(info.CMD))
            {
                info.Send = 0;
                info.CMD = null;
            }
            else
            {
                SendCmd(info);
            }
            gridControl1.ItemsSource = null;
            gridControl1.ItemsSource = items;
        }

        private bool SendCmd(TestInfoSource info)
        {
            Devices.IDevices device = null;
            if (info.CMD != null)
            {
                if (BCL.WPFComponent.UCMessageBox.Show("检查已完成，确定要重新发送嘛？".Language(), "提示".Language(), MessageBoxButton.OKCancel) != MessageBoxResult.OK)
                    return false;

                foreach (TabItem item in MainTag.Items)
                    if ((IDevices)item.Tag == info.CMD.Devices || item.Tag == null)
                        (item.Content as UCTestResult).RemoveCmds(info.CMD);

                device = info.CMD.Devices;
                if (info.CMD.Devices != null)
                    info.CMD.Devices.RemoveCommand(info.CMD.Id);
            }

            DevicesWPF.UCSelectDev form = new DevicesWPF.UCSelectDev() { Title = "选择设备" };
            if (form.ShowDialog(null) != MessageBoxResult.OK)
                return false;
            device = form.Device;

            info.Devices = 0;

            Devices.Command cmd = new Devices.Command
            {
                Id = info.ReportId,
                Name = info.ReportName,
                PetId = info.PetId,
                PetName = info.PetName,
                Code = info.ReportId,
                CustomerId=info.CustomerID,
                Customer = info.CustomerName,
                Date = DateTime.Now,
                Doctor = info.PhysicianName,
                DoctorId = info.PhysicianId,
                Tag=info.Version
            };
            RPTestPetInfo pet = logic.GetTestPet(info.PetId);
            if (pet == null)
            {
                BCL.WPFComponent.UCMessageBox.Show("宠物不存在或者已被删除！");
                return false;
            }
            cmd.Variety = pet.variety;
            cmd.KindOf = pet.KindOfType;
            cmd.Gender = pet.GenderType;
            //if(!string.IsNullOrEmpty(pet.genderText))
            //   cmd.Gender = pet.genderText == "母" ? Devices.GenderType.Female : Devices.GenderType.Male;
            cmd.Age = "1";

            if (pet.Birthdate?.Year > 2000)
                cmd.Age = ((DateTime.Now.Year - pet.Birthdate?.Year) * 12 + (DateTime.Now.Month - pet.Birthdate?.Month)).ToString();
            if (cmd.Age == "0")
                cmd.Age = "1";
            cmd.Weight = double.Parse(pet.weight);

            if (!device.AddCommand(cmd))
            {
                if(device.Error!=null)
                      BCLApplication.log?.Error(device.Error);
                UCMessageBox.Show("发送失败，请检查联接是否正常，参数是否正确");
                return false;
               
            }



            info.CMD = cmd;
            info.Send = 1;
            foreach (TabItem item in MainTag.Items)
                if ((IDevices)item.Tag == device || item.Tag == null)
                    (item.Content as UCTestResult).AddCmds(cmd);

            return true;
        }

        private bool CancelCmd(Command cmd)
        {
            if (BCL.WPFComponent.UCMessageBox.Show("确定要取消检查嘛？".Language(), "提示".Language(), MessageBoxButton.OKCancel) != MessageBoxResult.OK)
                return false;
            if (cmd != null)
                cmd.Devices.RemoveCommand(cmd.Id);
            foreach (TabItem item in MainTag.Items)
                if ((IDevices)item.Tag == cmd.Devices || item.Tag == null)
                    (item.Content as UCTestResult).RemoveCmds(cmd);

            return true;
        }

        private void GridControl1_Selected(object sender, SelectedCellsChangedEventArgs e)
        {
            if (!(gridControl1.SelectedItem is TestInfoSource info))
                return;
            ucTestResults?.ForEach(o => o.SelectConnamd(info.CMD));
        }

        private void TextBlock_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (!(gridControl1.SelectedItem is TestInfoSource info))
                return;


            RPTestPetInfo pet = logic.GetTestPet(info.PetId);
            canvasSelectTest.Visibility = Visibility.Visible;

            Point point = MainGird.TransformToDescendant(sender as TextBlock).Transform(new Point(0, 0));
/*            if (Math.Abs(point.Y) + canvasSelectTest.ActualHeight > MainGird.ActualHeight)
                point.Y = MainGird.ActualHeight - canvasSelectTest.ActualHeight;*/
            /*canvasSelectTest.Margin = new Thickness(440, Math.Abs(point.Y),0,0);*/
            canvasSelectTest.Margin = new Thickness(440, 200,0,0);

            GirdPetInfo.IsEnabled = info.Send == 0;

            //添加绑定
            if (ComboBoxPetSex.ItemsSource == null)
            {
                rpPetTypes= logic.GetPetType();
                rpSexs= logic.GetPetSex();
                rPBreedDatas = logic.GetPetBreed();

                ComboBoxPetSex.ItemsSource = rpSexs;
                ComboBoxPetSex.DisplayMemberPath = "codeName";
                
                ComboBoxPetType.ItemsSource = rpPetTypes;
                ComboBoxPetType.DisplayMemberPath = "codeName";

                ComboBoxPetBreed.DisplayMemberPath = "codeName";
            }

            // 点击宠物姓名之后初期化
            TextBlockPetName.Text = pet.petName; // 弹窗名 显示宠物名称
            ComboBoxPetSex.SelectedIndex = rpSexs.FindIndex(o=>o.codeValue==pet.gender);

            ComboBoxPetType.SelectedIndex = rpPetTypes.FindIndex(o => o.codeValue == pet.KindOF);

            List<RPDataDic> datas = ComboBoxPetBreed.ItemsSource as List<RPDataDic>;
            if(datas!=null)
                ComboBoxPetBreed.SelectedIndex = datas.FindIndex(o => o.codeValue == pet.petBreed);

            DatePickerPetBirthday.SelectedDate = DateTime.Parse(pet.birthdate);
            TextBoxPetWeight.Text = pet.weight;


        }

        /// <summary>
        /// 保存宠物信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImageButton_Click(object sender, RoutedEventArgs e)
        {
            if (!(gridControl1.SelectedItem is TestInfoSource info))
                return;

            editPetInfo petInfo = new editPetInfo();// pet.PetID.ToString();
            petInfo.id = info.PetId.ToString();

            petInfo.petSex = (ComboBoxPetSex.SelectedItem as RPDataDic).codeValue;
            petInfo.petType= (ComboBoxPetType.SelectedItem as RPDataDic).codeValue;
            petInfo.petBreed= (ComboBoxPetBreed.SelectedItem as RPDataDic).codeValue;
            petInfo.weight = TextBoxPetWeight.Text;


            //TimeSpan date =DateTime.Now-(DateTime)DatePickerPetBirthday.SelectedDate;
            DateTime pet_birth = (DateTime)DatePickerPetBirthday.SelectedDate;
            DateTime getnow = DateTime.Now;
            GetAgeByBirthday(pet_birth, getnow, out int year, out int month, out int day);
            petInfo.ageYear = year.ToString();
            petInfo.ageMonth = month.ToString();//   date.Month.ToString();
            petInfo.ageDay = day.ToString();

            //petInfo.ageYear = (date.Days / 365).ToString();
            //petInfo.ageMonth = (date.Days % 365 / 30).ToString();//   date.Month.ToString();
            //petInfo.ageDay = (date.Days % 365 % 30).ToString();

            string msg = logic.EditPetInfo(petInfo);
            if (msg == null)
                System.Windows.MessageBox.Show("保存失败!原因未知");
            else if(msg != "")
                System.Windows.MessageBox.Show(msg);
            else
            {
                System.Windows.MessageBox.Show("保存成功");
                canvasSelectTest.Visibility = Visibility.Collapsed;
            }

        }


        // 添加计算年纪的方法。HFY
        public void GetAgeByBirthday(DateTime birthday, DateTime now, out int year, out int month, out int day)

        {

            //生日的年，月，日
            int birthdayYear = birthday.Year;
            int birthdayMonth = birthday.Month;
            int birthdayDay = birthday.Day;

            //当前时间的年,月,日
            int nowYear = now.Year;
            int nowMonth = now.Month;
            int nowDay = now.Day;

            //得到天
            if (nowDay >= birthdayDay)

            {
                day = nowDay - birthdayDay;
            }
            else
            {
                nowMonth -= 1;
                day = GetDay(nowMonth, nowYear) + nowDay - birthdayDay;
            }
            //得到月
            if (nowMonth >= birthdayMonth)
            {
                month = nowMonth - birthdayMonth;
            }
            else
            {
                nowYear -= 1;
                month = 12 + nowMonth - birthdayMonth;
            }
            //得到年
            year = nowYear - birthdayYear;
        }
        /// 获取天数
        public int GetDay(int month, int year)
        {
            int day = 0;
            switch (month)
            {
                case 1:

                case 3:

                case 5:

                case 7:

                case 8:

                case 10:

                case 12:

                    day = 31;

                    break;

                case 2:

                    //闰年天，平年天
                    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
                    {
                        day = 29;
                    }
                    else
                    {
                        day = 28;
                    }
                    break;

                case 4:

                case 6:

                case 9:

                case 11:

                    day = 30;

                    break;
            }
            return day;
        }


        private void Border_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (canvasSelectTest.Visibility == Visibility.Visible)
                canvasSelectTest.Visibility = Visibility.Collapsed;
        }

        private void TextBlock_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
        }

        private void ComboBoxPetType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RPDataDic rPDataDic = ComboBoxPetType.SelectedItem as RPDataDic;
            if (rPDataDic == null)
                return;
            if (rPBreedDatas == null)
                return;
            switch (rPDataDic.codeValue)
            {
                case "dog":
                    ComboBoxPetBreed.ItemsSource = rPBreedDatas.dogBreed;
                    ComboBoxPetBreed.SelectedIndex = 0;
                    return;
                case "cat":
                    ComboBoxPetBreed.ItemsSource = rPBreedDatas.catBreed;
                    ComboBoxPetBreed.SelectedIndex = 0;
                    return;
                default:
                    ComboBoxPetBreed.ItemsSource = rPBreedDatas.otherBreed;
                    ComboBoxPetBreed.SelectedIndex = 0;
                    return;
            }

        }
    }
}
